/*
 * jQuery CreateNode Plugin (v1.1)
 * By Sylvain MATHIEU (www.sylvain-mathieu.com) for Zenexity (zenexity.fr)
 * MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

(function($) {

    $.cdn = {
        basicTags: [
            "div","span","h1","h2","h3","h4","h5","h6","p","ul","li","a","br","img","strong","em",
            "form","label","input","select","option","textarea","button",
            "table","tr","th","td","dl","dt","dd"
        ],
        startNode: function() {
            return $(document.createElement("div"));
        },
        addTag: function() {
            var tagName = this;
            if(!$.fn["_"+tagName+"_"]) {
                $.fn["_"+tagName+"_"] = function(attrs) {
                    return this._tag_(tagName, attrs);
                };
                $.fn["_"+tagName] = function(attrs) {
                    return this._tag(tagName, attrs);
                };
                $.fn[tagName+"_"] = function() {
                    return this.tag_(tagName);
                };
                $["_"+tagName+"_"] = function(attrs) {
                    return $.cdn.startNode()._tag_(tagName, attrs);
                };
                $["_"+tagName] = function(attrs) {
                    return $.cdn.startNode()._tag(tagName, attrs);
                };
            }
        },
        createTags: function(tags) {
            $(tags).each($.cdn.addTag);
        }
    };

    $.fn.applyAttrs = function(attrs) {
        var attrName;
        for(attrName in attrs) this.attr(attrName,attrs[attrName]);
        return this;
    };

    $.fn._tag_ = function(tagName, attrs) {
        $(document.createElement(tagName)).applyAttrs(attrs).appendTo(this);
        return this;
    };

    $.fn._tag = function(tagName, attrs) {
        return $(document.createElement(tagName)).applyAttrs(attrs).appendTo(this);
    };

    $.fn.tag_ = function(tagName) {
        return this.parent();
    };

    $.fn._append_ = function(text) {
        this.append(text);
        return this;
    };
 
    $.fn._appendTo_ = function(node) {
        this.contents().each(function() { $(this).appendTo(node); });
        return node;
    }

    $.fn._if_ = function(cond, _then, _else) {
        if (cond) _then._appendTo_(this);
        else if (_else != undefined) _else._appendTo_(this);
        return this;
    }

    $._append_ = function(text) {
        return $.cdn.startNode()._append_(text);
    };

    $._if_ = function(cond, _then, _else) {
        return $.cdn.startNode()._if_(cond, _then, _else);
    };

    $(document).ready(function(){
        $.cdn.createTags($.cdn.basicTags);
    });

})(jQuery);

